package com.fin.zw.intelligentbot.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/api/file")
@Api(value = "文件管理", description = "文件管理")
public class FileController {

    @Value("${file.record}")
    private String recordFileUrl;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传", notes = "文件上传")
    public ResponseEntity<Void> fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalName = file.getOriginalFilename();
        File outFile = new File(recordFileUrl);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        refileName(recordFileUrl + originalName);
        OutputStream ot = new FileOutputStream(recordFileUrl + File.separator + originalName);
        byte[] buffer = new byte[1024];
        int len;
        while ((-1 != (len = inputStream.read(buffer)))) {
            ot.write(buffer, 0, len);
        }
        ot.close();
        return ResponseEntity.ok().build();
    }

    public void refileName(String path) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        File f = new File(path);
        if (f.exists()) {
            String originalName = f.getName();
            String extensionName = originalName.substring(originalName.lastIndexOf(".") + 1);
            String newName = originalName.substring(0, originalName.lastIndexOf(".")) + "_" + df.format(new Date()) + "." + extensionName;
            File newFile = new File(f.getParent() + File.separator + newName);
            f.renameTo(newFile);
        }


    }
}
